'use strict';
const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
    env: cloudbase.SYMBOL_CURRENT_ENV
});
const db = app.database();
const _ = db.command;

exports.main = async (event, context) => {
    var _pageSize = 10;
    var _pageNum = 1;
    var query = {}
    if (event.pageNum != undefined && event.pageNum != null) {
        _pageNum = event.pageNum
    }
    if (event.pageSize != undefined && event.pageSize != null) {
        _pageSize = event.pageSize
    }
    if (event.searchCode != undefined && event.searchCode != null && event.searchCode != '') {
        query.name = new db.RegExp({
        regexp: searchCode
        })
    }

    return new Promise((resolve, reject) => {
        db.collection('dropPoint').aggregate().match({})
        .lookup({
            from: 'device',
            localField: '_id',
            foreignField: 'drop_point._id',
            as: 'devices'
        })
        .skip((_pageNum - 1) * _pageSize).limit(_pageSize).end()
        .then(res => {
            let data = res.data
            db.collection('dropPoint').where(query).count().then(res => {
                resolve({data: data, total:res.total})
            }).catch(err => {
                reject(err)
            })
        }).catch(err => {
            reject(err)
        })
    })
};
